<?php
namespace app\common\logic;

use app\common\exception\FailException;
use think\Controller;

class Card extends Controller
{
      public function card_list($usertype,$uid,$default=0,$page=1,$num=20){
          $where=[];
          if($default){

              $where['default']=$default;
          }

          return \app\common\model\Card::where("uid",$uid)->where("usertype",$usertype)->where("status",1)->where($where)->page($page,$num)->order("addtime desc")->select();

      }


      public function add_card($uid,$pay_password,$card,$bankname,$name,$usertype){

          $userdata=\app\common\model\User::where("id",$uid)->where("status",1)->find();

          if(!$userdata['pay_password']){

              throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
          }

          if($userdata['pay_password']!=md5($pay_password)){
              throw new FailException(["code"=>201,"msg"=>"支付密码错误","errorCode"=>404]);
          }

        $carddata = \app\common\model\Card::where("uid",$uid)->where("usertype",$usertype)->where("status",1)->order("addtime desc")->select();
        $default=0;
        if(!$carddata){
            $default=1;
        }


        $cardinfo = \app\common\model\Card::where("uid",$uid)->where("usertype",$usertype)->where("status",1)->where("card",$card)->find();

        if($cardinfo){
            throw new FailException(["code"=>201,"msg"=>"该银行卡号存在，请勿重复添加","errorCode"=>404]);
        }


       $data= \app\common\model\Card::create(
            [
               "uid"=>$uid,
               "card"=>$card,
               "bankname"=>$bankname,
               "name"=>$name,
               "default"=>$default,
               "usertype"=>$usertype,
               "addtime"=>time()
            ]
        );

         return $data;
       }

    public function del_card($uid,$pay_password,$card_id,$usertype){

        $userdata=\app\common\model\User::where("id",$uid)->where("status",1)->find();
        if($userdata['pay_password']!=md5($pay_password)){
            throw new FailException(["code"=>201,"msg"=>"支付密码错误","errorCode"=>404]);
        }

        return \app\common\model\Card::where("uid",$uid)->where("usertype",$usertype)->where("id",$card_id)->delete();

    }
}